import { useMemo, useRef, useState } from "react";
import styles from "./index.module.less";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { getDockDetail, getPathByScID } from "@/api/modules/platform";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import AMap from "@/components/AMap";
import { Descriptions, message } from 'antd';
import { getTableColumns } from "./constant";
import cs from 'classnames';
import { map } from 'lodash';
import { getJointTypeDict } from "@/api/modules/dict";
import SuperTable from "@/components/SuperTable";
import { getAllOrgList, getDictByCode } from "@/api/modules/dict";
import { find } from 'lodash';
import { isValidLngLatArray } from "@/utils/utils";
import { PageContainer } from '@ant-design/pro-layout';
import { unbindJoint } from "@/api/modules/platform";
export default () => {
	const { navigate, query } = useUrl();
	const detailId = query.get("detailId");
	const [detailInfo, setDetailInfo] = useState<any>({});
	const [siteList, setSiteList] = useState<any>([]);
	const [rectList, setRectList] = useState<any>([]);
	const [loopPaths, setLoopPaths] = useState<any>([]);

	const { loading: loadingDetail, runAsync: getDetailAsync, data: walkDetailInfo } = useRequest(getDockDetail, { manual: true });
	const { data: data1 } = useRequest(() => getJointTypeDict({ parentId: 0, code: "POINT_TYPE" }))

	const { data: orgList } = useRequest(() => getAllOrgList({ page: { pageNum: 1, pageSize: 100 }}));
	const { data: areaTypeList } = useRequest(() => getDictByCode({ parentId: 0, code: "AREA_TYPE" }));
	const { data: route } = useRequest(() => getPathByScID({ id: detailId }));

	const siteTableList = walkDetailInfo?.data?.sites
	const jointTypeList = data1?.data
	const routeData = route?.data

	useMemo(() => {
		if(routeData && routeData.length > 0){
			const paths: any[] = [];
			routeData.forEach((route: any) => {
				if(route.routeSubList && route.routeSubList.length > 0){
					const routePaths = map(route.routeSubList, (item: any) => {
						return {
							path: JSON.parse(item.routeInfo),
							strokeColor: route.color
						}
					});
					paths.push(...routePaths);
				}
			});
			setLoopPaths(paths);
		}
	}, [routeData])

	useEffect(() => {
		if (!detailId) return;
		getDetailAsync({ id: detailId }).then((res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data?.scene ?? {};
				console.log(res?.data, "res?.data?.sites");
				const markers = map(res?.data?.sites, (site: any) => {
					return {
						position: site.lonLat?.split(",")
					}
				}).filter(Boolean);
				const position = JSON.parse(res?.data?.scene?.points);
				const rects = [{
					path: isValidLngLatArray(position) ? position : []
				}]
				setRectList(rects);
				setDetailInfo(data);
				setSiteList(markers);
			}
		});
	}, []);


	const unbind = {
		label: "解绑",
		value: "unbind"
	}

	const handleUnbindJoint = (record: any) => {
		unbindJoint({ id: record.id }).then((res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				message.success("解绑成功");
				getDetailAsync({ id: detailId });
			}
		});
	}

	const newColumns = [
		...getTableColumns({ jointTypeList }),
		{
			title: "操作",
 			valueType: 'option',
			width: 80,
			fixed: "right",
			dataIndex: "action-render",
			onClick: (key: string, record: any) => {
				switch (key) {
					case "unbind":
						handleUnbindJoint(record)
						break;
				}
			},
			options: (record: any) => {
				return [unbind];
			}
		}
	];

	return (
		<PageContainer
			title=" "
			breadcrumb={{
				routes: [
					{ href: '/platform/dock', breadcrumbName: '月台管理' },
					{ href: '', breadcrumbName: '月台详情' },
				],
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={cs(styles.detailContainer, 'detailContainer')}>
					<div className={styles.container}>
						<div className={styles.content_wrap}>
							<div className={styles.content}>
								<div className={styles.moduleTitle}>基本信息</div>
								<Descriptions title="" column={1} labelStyle={{width: '100px'}}>
									<Descriptions.Item label="月台名称">{detailInfo.scName || '-'}</Descriptions.Item>
									<Descriptions.Item label="月台类型">{find(areaTypeList?.data, (item: any) => `${item.value}` === `${detailInfo?.type}`)?.label || '-'}</Descriptions.Item>
									<Descriptions.Item label="所属组织">{find(orgList?.data, (item: any) => item.id === detailInfo?.createOrgId)?.name || '-'}</Descriptions.Item>
									<Descriptions.Item label="接驳点数量">{detailInfo.siteCount || '-'}</Descriptions.Item>
									<Descriptions.Item label="范围区域">{detailInfo.points || '-'}</Descriptions.Item>
								</Descriptions>
							</div>
						</div>
						<div className={cs(styles.content_wrap, styles.mt_20)}>
							<div className={styles.content}>
								<div className={styles.moduleTitle}>
									<div className={styles.title}>关联接驳点信息</div>
								</div>
								<SuperTable
									className={cs([styles.tableContainer])}
									columns={newColumns}
									toolBarRender={false}
									search={false}
									dataSource={siteTableList}
								/>
							</div>
						</div>
					</div>
					<div className={styles.mapBox}>
						<div className={styles.moduleTitle}>地图预览</div>
						<div className={styles.mapOuter}>
							<AMap 
								markers={siteList}
								polygons={rectList}
								polylinePaths={loopPaths}
							/>
						</div>
					</div>
				</div>
			</Loading>
		</PageContainer>
	);
};
